/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.handler;

import cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.common.RuntimeEnv;
import static cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.common.RuntimeEnv.jsonQueue;
import cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.utils.FileTools;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author Administrator
 */
public class AudioDownloadHandler implements Runnable {

    static Logger logger = Logger.getLogger(AudioDownloadHandler.class.getName());
    public String respnseDir;

    public AudioDownloadHandler(String respnseDir) {
        this.respnseDir = respnseDir;
    }

    @Override
    public void run() {
        while (true) {
            String url_md5 = null;
            long start = System.currentTimeMillis();
            try {

                String json = jsonQueue.poll(20, TimeUnit.MILLISECONDS);
                if (json == null || "\n".equals(json) || "".equals(json)) {
//                    logger.info("get json is null");
                } else {
                    logger.info(start+"===="+json);
                    JSONObject jsonObj = JSONObject.parseObject(json);
                    String url = jsonObj.getString("url");//真实下载地址
                    url_md5 = jsonObj.getString("url_md5");
                    InputStream audioStream = null;
                    boolean successFlag = false;
                    try {
                        int timeOut = Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.timeOut));
                        audioStream = org.apache.http.client.fluent.Request.Get(url)
                                .execute().returnContent().asStream();
                        successFlag = true;
                    } catch (Exception ex) {
                        logger.error(url_md5 + ex.getMessage(), ex);
                        if (ex.getMessage().equals("Forbidden")) {
                            String responseCode = "{\"code\":-7,\"errorinfo\":\"音频文件下载失败，互联网区返回400" + ex.getMessage() + "\"}";
                            audioStream = new ByteArrayInputStream(responseCode.getBytes("UTF-8"));
                            logger.error(url_md5 + " is " + ex.getMessage() + "to download", ex);
                        } else {
                            audioStream = new ByteArrayInputStream("{\"code\":-6,\"errorinfo\":\"音频下载超出预定等待时间，请稍候重试\"}".getBytes("UTF-8"));
                        }
                    }
                    //音频文件成功下载，使用原来的后缀名，否则使用json进行标明
                    String fileSuffix = ".json";
                    if (successFlag) {
                        fileSuffix = FileTools.suffix(url);
                    }
                    File file = new File(respnseDir + url_md5 + fileSuffix);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
                    int bytesReadIn = 0;
                    byte[] bytesContent = new byte[1024 * 2];

                    while ((bytesReadIn = audioStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                        bos.write(bytesContent, 0, bytesReadIn);
                    }
                    bos.flush();
                    fileOutputStream.close();
                    bos.close();
                    logger.info("download use time (ms): " + (System.currentTimeMillis() - start));
                }

            } catch (InterruptedException ex) {
                logger.error(url_md5 + ex.getMessage(), ex);
            } catch (IOException ex) {
                logger.error(url_md5 + ex.getMessage());
            } finally {

            }
        }
    }

}
